package com.atguigu.common.config;

import com.atguigu.common.enums.BizCodeEnum;
import com.atguigu.common.exception.BizException;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lsua
 * @date 2022-09-23 20:46
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BindException.class)
    public R handleValidException(BindException e) {
        log.error("校验异常", e);
        Map<String, String> errorMap = new HashMap<>();
        e.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION).put("data", errorMap);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        log.error("校验异常", e);
        BindingResult bindingResult = e.getBindingResult();

        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        return R.error(BizCodeEnum.VALID_EXCEPTION).put("data", errorMap);
    }

    @ExceptionHandler(BizException.class)
    public R businessExceptionHandler(BizException e) {
        log.error("业务异常", e);
        return R.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) {
        log.error("未知异常", e);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION).put("data", e.getMessage());
    }

}
